<template>
  <div class="json-validator">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>JSON 验证器</span>
      </div>
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="JSON 数据" prop="jsonData">
          <el-input
            type="textarea"
            :rows="10"
            placeholder="请输入JSON数据"
            v-model="form.jsonData">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="validateJson">验证</el-button>
          <el-button type="success" @click="saveJson" :disabled="!isValidJson" :loading="saving">保存</el-button>
        </el-form-item>
      </el-form>
      <div v-if="validationMessage" :class="['validation-message', isValidJson ? 'valid' : 'invalid']">
        {{ validationMessage }}
      </div>
    </el-card>
  </div>
</template>

<script>
import { jsonApi } from '../api';

export default {
  name: 'JsonValidator',
  data() {
    return {
      form: {
        jsonData: ''
      },
      rules: {
        jsonData: [
          { required: true, message: '请输入JSON数据', trigger: 'blur' }
        ]
      },
      isValidJson: false,
      validationMessage: '',
      saving: false,
      loading: false
    }
  },
  created() {
    // 页面创建时加载JSON数据
    this.loadJsonData();
  },
  methods: {
    // 加载JSON数据
    loadJsonData() {
      this.loading = true;
      this.validationMessage = '正在加载数据...';
      
      jsonApi.getJsonData()
        .then(response => {
          if (response.code === 0 && response.data) {
            // 如果数据是对象，转换为格式化的JSON字符串
            if (typeof response.data.json_data === 'object') {
              this.form.jsonData = JSON.stringify(response.data.json_data, null, 2);
            } else {
              // 如果是字符串，尝试解析并格式化
              try {
                const jsonObj = JSON.parse(response.data.json_data);
                this.form.jsonData = JSON.stringify(jsonObj, null, 2);
              } catch (e) {
                // 如果解析失败，直接使用原始字符串
                this.form.jsonData = response.data.json_data;
              }
            }
            this.validateJson();
            this.$message.success('已加载最新的JSON数据');
          } else if (response.code === 1 && response.message === '数据库中没有JSON数据') {
            this.validationMessage = '数据库中没有JSON数据，请输入并保存';
          } else {
            this.$message.warning(`加载数据失败: ${response.message}`);
          }
        })
        .catch(error => {
          console.error('加载JSON数据时出错:', error);
          this.$message.error('加载失败，请检查网络连接或服务器状态');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    validateJson() {
      try {
        if (!this.form.jsonData.trim()) {
          this.validationMessage = '请输入JSON数据';
          this.isValidJson = false;
          return;
        }
        
        JSON.parse(this.form.jsonData);
        this.validationMessage = 'JSON格式有效';
        this.isValidJson = true;
      } catch (e) {
        this.validationMessage = `JSON格式无效: ${e.message}`;
        this.isValidJson = false;
      }
    },
    saveJson() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.isValidJson) {
            this.$message.error('请先确保JSON格式有效');
            return;
          }
          
          this.saving = true;
          jsonApi.saveJsonData(this.form.jsonData)
            .then(response => {
              if (response.code === 0) {
                this.$message.success(response.message || 'JSON数据保存成功');
                // 更新Vuex中的数据
                this.$store.commit('setJsonData', this.form.jsonData);
              } else {
                this.$message.error(`保存失败: ${response.message}`);
              }
            })
            .catch(error => {
              console.error('保存JSON数据时出错:', error);
              this.$message.error('保存失败，请检查网络连接或服务器状态');
            })
            .finally(() => {
              this.saving = false;
            });
        }
      });
    }
  }
}
</script>

<style scoped>
.json-validator {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
.validation-message {
  margin-top: 15px;
  padding: 10px;
  border-radius: 4px;
}
.valid {
  background-color: #f0f9eb;
  color: #67c23a;
}
.invalid {
  background-color: #fef0f0;
  color: #f56c6c;
}
</style>